package top.truism.stack;

import java.util.Stack;

/**
 * 写一个递归函数来实现栈的逆序
 */
public class ReverseStack {

    /**
     * 实现对栈的逆序
     * @param stack
     */
    public static void reverse(Stack stack) {

        if(stack.isEmpty()) {
            return;
        }
        Object obj = getAndRemoveLast(stack);
        reverse(stack);
        stack.push(obj);
    }

    /**
     * 获取栈底元素并从栈中删除
     * @param stack
     * @param <T>
     * @return
     */
    public static <T> T getAndRemoveLast(Stack<T> stack) {

        T result = stack.pop();
        if(stack.isEmpty()) {
            return result;
        }else {
            T last = getAndRemoveLast(stack);
            stack.push(result);
            return last;
        }
    }

}
